/*
 * @Author: Salaing
 * @Date: 2024-08-24 21:06:04
 * @LastEditors: Salaing
 * @LastEditTime: 2024-09-02 23:38:25
 * @Description: file content 为了兼容.parentLists[null]和children[null]这些情况加了一些方法
 */
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'umi';
import OrgTree from 'react-org-tree';

function Tree({ getDepartmentDetail }) {
  // 根节点只显示没有父级部门的
  const departmentList = useSelector((state) =>
    JSON.parse(
      JSON.stringify(
        state.department.departmentList.filter(
          (item) =>
            item.parentLists.some((v) => v === null) ||
            !item.parentLists.length,
        ),
      ),
    ),
  );
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch({
      type: 'department/_initDepartmentList',
      payload: {},
    });
  }, []);

  // function removeNullsFromChildren(items) {
  //   return items.map((item) => {
  //     // 如果当前项有children数组
  //     if (Array.isArray(item.children)) {
  //       // 过滤掉children中的null值，并递归处理剩余的children
  //       item.children = removeNullsFromChildren(
  //         item.children.filter((child) => child !== null),
  //       );
  //     }
  //     // 返回修改后的项
  //     return item;
  //   });
  // }
  const addProps = (list) => {
    list.forEach((item) => {
      if (item && item.departmentName !== null && item !== null) {
        item.label = item.departmentName;
        item.id = item._id;
        if (
          item.children &&
          item.children.length &&
          item.children.every((child) => child !== null)
        ) {
          addProps(item.children);
        }
      }
    });
  };
  addProps(departmentList);

  //- 获取当前选定的内容
  const selectData = (e, data) => {
    getDepartmentDetail(data.id, data.departmentName);
  };

  const renderData = {
    id: -1,
    label: '公司组织架构图',
    children: departmentList,
  };

  return (
    <OrgTree
      data={renderData}
      horizontal={false}
      collapsable={false}
      expandAll={true}
      onClick={selectData}
    />
  );
}

export default Tree;
